package io.kiki.sba.registry.server.data_store.resource;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.metrics.ReporterUtils;
import io.kiki.sba.registry.server.data_store.bootstrap.Bootstrap;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

/**
 * @author shangyu.wh
 * @version $Id: HealthResource.java, v 0.1 2018-10-19 14:56 shangyu.wh Exp $
 */
@Path("health")
public class HealthResource {

    @Autowired
    Bootstrap bootstrap;

    @PostConstruct
    public void init() {
        MetricRegistry metrics = new MetricRegistry();
        metrics.register("healthCheck", (Gauge<Response>) () -> getHealthCheckResult());
        ReporterUtils.startSlf4jReporter(60, metrics);
    }

    @GET
    @Path("check")
    @Produces(MediaType.APPLICATION_JSON)
    public javax.ws.rs.core.Response checkHealth() {

        ResponseBuilder builder = javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.OK);
        Response response = getHealthCheckResult();
        builder.entity(response);
        if (!response.isSuccess()) {
            builder.status(Status.INTERNAL_SERVER_ERROR);
        }

        return builder.build();
    }

    private Response getHealthCheckResult() {
        Response response;

        StringBuilder sb = new StringBuilder("DataServerBoot ");

        boolean start = bootstrap.getServerForSessionStarted();
        boolean ret = start;
        sb.append("severForSession:").append(start);

        start = bootstrap.getServerForDataSyncStarted();
        ret = ret && start;
        sb.append(", severForDataSync:").append(start);

        start = bootstrap.getHttpServerStarted();
        ret = ret && start;
        sb.append(", httpServer:").append(start);

        start = bootstrap.getSchedulerStarted();
        ret = ret && start;
        sb.append(", schedulerStarted:").append(start);

        if (ret) {
            response = Response.buildSuccessResponse(sb.toString());
        } else {
            response = Response.buildFailedResponse(sb.toString());
        }
        return response;
    }
}
